<?php
// -----------------------------------------------------------------------------
// include
// -----------------------------------------------------------------------------

include "../config/config.php";
include "../auth.php";
include "../DBManager.php";
include "GenerateCurrentDayCardBody.php";
require '../vendor/autoload.php';

use Overtrue\ChineseCalendar\Calendar;

// -----------------------------------------------------------------------------
// 对象初始化
// -----------------------------------------------------------------------------

$dbPath = "../" . $dbPath; // 不加这行语句的话会报错，提示找不到对应路径
$db = new DBManager("sqlite:" . $dbPath);

$gcb = new GenerateCurrentDayCardBody();
$calendar = new Calendar();

// -----------------------------------------------------------------------------
// 函数定义
// -----------------------------------------------------------------------------

/**
 * 返回指定日期的所属年份
 * @param string $date
 * @return string
 */
function getYear(string $date):string
{
    return date("o", strtotime($date));
}

/**
 * 返回指定日期在一年中的周数
 * @param string $date
 * @return string
 */
function getWeek(string $date):string
{
    return date("W", strtotime($date));
}

function getDayOfWeek(string $date):string
{
    $days = ["日", "一", "二", "三", "四", "五", "六"];
    $dt = new DateTime($date);
    $index = $dt->format("w");
    return $days[$index];
}

/**
 * @param string $weekOfYear 形如：2024-W31
 * @return string
 */
function getMonday(string $weekOfYear):string
{
    $monday = date("Ymd", strtotime('monday this week', strtotime($weekOfYear)));
    return $monday;
}

function getPreMonday(string $currentMonday):string
{

    $currentMondayObj = new DateTimeImmutable($currentMonday);
    $interval = new DateInterval('P1W');

    $preMondayObj = $currentMondayObj->sub($interval);
    return $preMondayObj->format("Ymd");

}

function getNextMonday(string $currentMonday):string
{

    $currentMondayObj = new DateTimeImmutable($currentMonday);
    $interval = new DateInterval('P1W');

    $nextMondayObj = $currentMondayObj->add($interval);
    return $nextMondayObj->format("Ymd");

}

// -----------------------------------------------------------------------------
// 时区设置
// -----------------------------------------------------------------------------

// 这里的时区设置语句不能移到「访问设置」的后面
// 因为「访问设置」中用到了 date()
date_default_timezone_set($region);

// -----------------------------------------------------------------------------
// 访问设置
// -----------------------------------------------------------------------------

// 今天所在的周

$todayStr = date("Ymd");
$yearOfThisWeek = getYear($todayStr);
$weekWithoutYearOfThisWeek = getWeek($todayStr);
$weekWithYearOfThisWeek = $yearOfThisWeek . "-W" . $weekWithoutYearOfThisWeek;
$mondayOfThisWeek = getmonday($weekWithYearOfThisWeek);

// 当前周，不一定是今天所在的周

if (isset($_GET["from"])) {

    $from = $_GET["from"];

    if ($from == "thisWeek") {
        $weekWithYearOfCurrentWeek = $weekWithYearOfThisWeek;
    }

    if ($from == "nextWeek") {
        $nextMonday = getNextMonday($mondayOfThisWeek);
        $yearOfNextWeek = getYear($nextMonday);
        $weekWithoutYearOfNextWeek = getWeek($nextMonday);
        $weekWithYearOfNextWeek = $yearOfNextWeek . "-W" . $weekWithoutYearOfNextWeek;
        $weekWithYearOfCurrentWeek = $weekWithYearOfNextWeek;
    }

    if ($from == "date") {
        if (isset($_GET["date"])) {
            $date = $_GET["date"];
            // 这里的 $yearOfCurrentWeek 和 $weekWithoutYearOfCurrentWeek 的值，
            // 后续还要再求一遍，有点重复了，但也是不得已而为之
            $yearOfCurrentWeek = getYear($date);
            $weekWithoutYearOfCurrentWeek = getWeek($date);
            $weekWithYearOfCurrentWeek = $yearOfCurrentWeek . "-W" . $weekWithoutYearOfCurrentWeek;
        } else {
            exit("需要传入有效的参数！");
        }
    }

} else {

    if (isset($_GET["week"])) {
        $weekWithYearOfCurrentWeek = $_GET["week"]; // 形如：2024-W01
    } else {
        exit("需要传入有效的参数！");
    }

}

$yearOfCurrentWeek = getYear($weekWithYearOfCurrentWeek);
$weekWithoutYearOfCurrentWeek = getWeek($weekWithYearOfCurrentWeek);
$mondayOfCurrentWeek = getMonday($weekWithYearOfCurrentWeek);

// 当前周的上一周

$mondayOfPreWeek = getPreMonday($mondayOfCurrentWeek);
$yearOfPreWeek = getYear($mondayOfPreWeek);
$weekWithoutYearOfPreWeek = getWeek($mondayOfPreWeek);
$weekWithYearOfPreWeek = $yearOfPreWeek . "-W" . $weekWithoutYearOfPreWeek;

// 当前周的下一周

$mondayOfNextWeek = getNextMonday($mondayOfCurrentWeek);
$yearOfNextWeek = getYear($mondayOfNextWeek);
$weekWithoutYearOfNextWeek = getWeek($mondayOfNextWeek);
$weekWithYearOfNextWeek = $yearOfNextWeek . "-W" . $weekWithoutYearOfNextWeek;

// -----------------------------------------------------------------------------
?>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>周视图</title>
    <link rel="stylesheet" href="../resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
    <style>
        h5 {
            margin-top: 4px;
            margin-bottom: 4px;
        }
        h6 {
            margin-top: 4px;
            margin-bottom: 4px;
        }
        .taskItem {
            cursor: pointer;
        }
        .taskTitle:hover {
            transform: scale(1.2); /* 放大到原来的1.2倍 */
            /* 可选：添加其他样式增强效果 */
            font-weight: bold;
            color: #2c3e50;
        }
    </style>
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<script src="../resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<script src="../resources/jQuery/jquery-3.5.1.js"></script>
<?php include "../globalNavbar.php"; ?>

<!-- ----------------------------------------------------------------------- -->

<!-- div container 开始 -->
<div class="container container-fluid mt-3 mb-5">

    <!-- 导航栏 开始 -->
    <div class="mt-3">
        <nav style="--bs-breadcrumb-divider: '>';" aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a class="text-decoration-none" href="<?php echo $homepage; ?>">首页</a></li>
                <li class="breadcrumb-item"><a class="text-decoration-none" href="index.php"><?php echo $linkTitleSpecific; ?></a></li>
                <li class="breadcrumb-item active">周</li>
            </ol>
        </nav>
    </div>
    <!-- 导航栏 结束 -->

    <div class="card">

        <div class="card-header">

            <div>

                <?php

                $str = "December 28th, " . $yearOfCurrentWeek;
                $totalWeeks = date('W', strtotime($str));
                $remainWeeks = $totalWeeks - $weekWithoutYearOfCurrentWeek;

                echo <<<BBB
                    {$yearOfCurrentWeek}年第{$weekWithoutYearOfCurrentWeek}周，共{$totalWeeks}周，剩{$remainWeeks}周。
                BBB;

                ?>

            </div>

            <hr class="mt-1 mb-1" />

            <div>

                <?php if ($weekWithYearOfCurrentWeek == $weekWithYearOfThisWeek): ?>
                    <a role="button" class="badge text-decoration-none text-bg-danger mx-1 viewThisWeek">本周</a>
                <?php else: ?>
                    <a role="button" class="badge text-decoration-none text-bg-primary mx-1 viewThisWeek">本周</a>
                <?php endif; ?>

                <a role="button" class="badge text-decoration-none text-bg-primary mx-1 viewPreWeek">上一周</a>
                <a role="button" class="badge text-decoration-none text-bg-primary mx-1 viewNextWeek">下一周</a>

                <span>
                    <span role="button" class="badge text-bg-secondary mx-1 my-1 closeAll">折叠</span>
                    <span role="button" class="badge text-bg-secondary mx-1 my-1 openAll">展开</span>
                </span>

            </div>

        </div>

    </div>

    <div class="mt-3">
        <form id="myForm" action="editTasksInMonthViewFormAction.php" method="POST">
            <div style="display: none">
                <input name="week" value="<?php echo $weekWithYearOfCurrentWeek; ?>" type="hidden">
            </div>
            <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
                <?php

                $monday = $mondayOfCurrentWeek;
                $tuesday = date("Ymd", strtotime('tuesday this week', strtotime($monday)));
                $wednesday = date("Ymd", strtotime('wednesday this week', strtotime($monday)));
                $thursday = date("Ymd", strtotime('thursday this week', strtotime($monday)));
                $friday = date("Ymd", strtotime('friday this week', strtotime($monday)));
                $saturday = date("Ymd", strtotime('saturday this week', strtotime($monday)));
                $sunday = date("Ymd", strtotime('sunday this week', strtotime($monday)));

                $arr = [$monday, $tuesday, $wednesday, $thursday, $friday, $saturday, $sunday];

                $counter = 0;
                while ($counter <= 6) {

                    $dateStr = $arr[$counter];
                    $dateObj = new DateTimeImmutable($dateStr);
                    $year = $dateObj->format('Y');
                    $month = $dateObj->format('m');
                    $day = $dateObj->format('d');
                    $result = $calendar->solar($year, $month, $day);
                    $monthLunarChinese = $result["lunar_month_chinese"];
                    $dayOfMonthLunarChinese = $result["lunar_day_chinese"];

                    $todayCardHeader = "";
                    $isToday = "";
                    if ($dateStr == $todayStr) {
                        $todayCardHeader = "bg-info";
                        $isToday = " （今天）";
                    }

                    $dayOfWeek = getDayOfWeek($dateStr);

                    $content = $gcb->getHtml($db, $dateStr);

                    $tabindex = $counter + 1;
                    echo <<<BBB
                        <div class="col mt-3">
                            <div class="card">
                                 <div class="card-header d-flex $todayCardHeader" role="button">
                                    <span class="fw-bold w-100"><a role="button" href="../viewByDate.php?date={$dateStr}" class="badge text-bg-warning mx-1 btnViewByDate text-decoration-none">{$dateStr}</a> | 周{$dayOfWeek} | {$monthLunarChinese}{$dayOfMonthLunarChinese} {$isToday}</span>
                                    <div class="flex-shrink-0">
                                        <span role="button" data-date="{$dateStr}" class="badge text-bg-dark btnViewHtml text-decoration-none">刷新</span>
                                        <span role="button" data-date="{$dateStr}" class="badge text-bg-dark btnEditText text-decoration-none">编辑</span>
                                    </div>
                                </div>
                                <div data-date="{$dateStr}" class="card-body showContent" style="height: 285px; overflow-y: auto;">
                                    <div class="view">{$content}</div>
                                    <textarea class="form-control editContent" 
                                              style="display: none;"
                                              data-date="{$dateStr}"
                                              rows="10"></textarea>
                                </div>
                            </div>
                        </div>
                    BBB;
                    $counter += 1;
                };
                ?>
            </div>
        </form>
    </div>

</div>
<!-- div container 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!-- 消息弹窗 开始 -->
<div aria-live="polite" aria-atomic="true" class="position-relative">
    <div class="toast-container position-fixed top-0 start-50 translate-middle-x">

        <div id="toastOne" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div id="toastHeader" class="toast-header bg-info">
                <strong class="me-auto">提示</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body bg-white">
                <p id="msgContent">需要显示的信息。</p>
            </div>
        </div>

    </div>
</div>
<!-- 消息弹窗 结束 -->

<!-- ----------------------------------------------------------------------- -->
<script src="../resources/jQuery/jquery-3.5.1.js"></script>
<script src="../resources/base64/functions.js"></script>
<!-- ----------------------------------------------------------------------- -->

<!--函数定义-->
<script>

    // 从数据库中读取指定日期内的「已完成的事务」
    function readFromFinished(date) {

        var url = "../ajax/readFromFinished.php?date=" + date

        $.get({
            url: url,
            async: false
        })
            .done(function( data ) {
                finishedTasksJsonString = data
            })
            .fail(function () {
                alert("请求失败。")
            });

    }

    // 向数据库中写入指定日期内的「已完成的事务」
    function writeToFinished(content, date) {

        var url = "../ajax/writeToFinished.php"

        $.post({
            url: url,
            data: {content: content, date: date},
            async: false
        })
            .done(function () {
                console.log("数据写入成功。")
            })
            .fail(function () {
                alert("请求失败。")
            })

    }

</script>

<!-- ----------------------------------------------------------------------- -->

<!--全局变量-->
<script>
    var finishedTasksJsonString = ""
</script>

<!-- ----------------------------------------------------------------------- -->

<!--事件处理-->
<script>

    $(".viewPreWeek").on("click", function () {
        var url = "weekView.php?week=<?php echo $weekWithYearOfPreWeek; ?>";
        window.open(url, "_self")
    })

    $(".viewNextWeek").on("click", function () {
        var url = "weekView.php?week=<?php echo $weekWithYearOfNextWeek; ?>";
        window.open(url, "_self")
    })

    $(".viewThisWeek").on("click", function () {
        var url = "weekView.php?week=<?php echo $weekWithYearOfThisWeek; ?>";
        window.open(url, "_self")
    })

    // 处理清空按钮事件
    $("#btnClear").on("click", function() {

        $("textarea").val("");

    });

    $(".card-header").on("click", function(event) {
        $(this).next().slideToggle("fast")
    })

    $(".closeAll").on("click", function () {
        $(".card-body").slideUp("fast")
    })

    $(".openAll").on("click", function () {
        $(".card-body").slideDown("fast")
    })

    $(".btnViewByDate").on("click", function (event) {
        event.stopPropagation()
    })

    $(".btnViewHtml").on("click", function (event) {

        var divToShowContent = $(this).parent().parent().next().children().first()
        var textarea = $(this).parent().parent().next().children().last()

        var date = $(this).data("date")
        var url = `ajax/getSpecificDayTasksHtml.php?date=${date}`

        $.get(url)
            .done(function( data ) {
                textarea.hide()
                divToShowContent.html(data)
                divToShowContent.show()
            })
            .fail(function () {
                alert("请求失败。")
            });

        event.stopPropagation()

    })

    $(".btnEditText").on("click", function (event) {

        var divToShowContent = $(this).parent().parent().next().children().first()
        var textarea = $(this).parent().parent().next().children().last()

        var date = $(this).data("date")
        var url = `ajax/getSpecificDayTasksText.php?date=${date}`

        $.get(url)
            .done(function( data ) {
                divToShowContent.hide()
                textarea.val(data)
                textarea.show()
                textarea.focus()
            })
            .fail(function () {
                alert("请求失败。")
            });

        event.stopPropagation()

    })

    $(document).on("click", ".showContent", function(event) {

        var divToShowContent = $(this).children().first()
        var textarea = $(this).children().last()

        var date = $(this).data("date")
        var url = `ajax/getSpecificDayTasksText.php?date=${date}`

        $.get(url)
            .done(function( data ) {
                divToShowContent.hide()
                textarea.val(data)
                textarea.show()
                textarea.focus()
            })
            .fail(function () {
                alert("请求失败。")
            });

    })

    $(document).on("click", ".editContent", function(event) {
        event.stopPropagation()
    })

    $(document).on("focusout", ".editContent", function(event) {

        var textarea = $(this)
        var btnShowContent = $(this).parent().prev().children().last().children().first()

        // .val() 后面要加正则表达式，不然 textarea 中的换行符不能通过 ajax 正常保存
        // 参考：https://api.jquery.com/val/#val
        var content = $(this).val().replace( /\r?\n/g, "\r\n" )
        var date = $(this).data("date")
        var url = `ajax/writeSpecificDayTasksText.php`

        $.post(url, {date: date, content: content})
            .done(function (data) {

                textarea.hide()
                btnShowContent.click()

                $("#msgContent").text(data)
                // $("#toastHeader").attr("class", "toast-header bg-info")
                const toast = new bootstrap.Toast(toastOne, {"delay": 1000})
                toast.show()

            })
            .fail(function () {
                alert("请求失败。")
            })

    })

    // 点击「待办事务描述文字」时，点击相应的复选框
    $(document).on("click", ".taskTitle", function(event) {
        $(this).prev().click()
        event.stopPropagation()
    })

    $(document).on("click", ".taskItem", function (event) {
        event.stopPropagation()
    })

    // 点击「待办事务描述文字」前面的「复选框」时执行
    $(document).on("change", ".taskItem", function(event) {
        // 获取当前复选框所在的日期卡片（通过 closest 定位到最近的 .showContent 容器，再取其 data-date）
        const $currentCard = $(this).closest(".showContent");
        const dateStr = $currentCard.data("date");
        console.log("当前日期卡片：" + dateStr);

        // 获取当前任务标题和复选框状态
        const taskTitle = $(this).next().text().trim();
        const isChecked = $(this).is(':checked');

        // 【核心优化】仅同步当前日期卡片内的同名任务
        $currentCard.find(".taskItem").each(function() {
            const currentTaskTitle = $(this).next().text().trim();
            if (currentTaskTitle === taskTitle) {
                $(this).prop("checked", isChecked);
            }
        });

        // 读取该日期的已完成任务列表
        readFromFinished(dateStr);

        let finishedTasks = [];
        if (finishedTasksJsonString !== "") {
            // 解码并解析已完成任务
            finishedTasksJsonString = b64_to_utf8(finishedTasksJsonString);
            finishedTasks = JSON.parse(finishedTasksJsonString);
        }

        if (isChecked) {
            // 选中时添加任务（去重检查）
            if (!finishedTasks.includes(taskTitle)) {
                finishedTasks.push(taskTitle);
            }
        } else {
            // 取消选中时移除任务（存在性检查）
            const index = finishedTasks.indexOf(taskTitle);
            if (index !== -1) {
                finishedTasks.splice(index, 1);
            }
        }

        // 编码并保存已完成任务列表
        finishedTasksJsonString = JSON.stringify(finishedTasks);
        finishedTasksJsonString = utf8_to_b64(finishedTasksJsonString);
        writeToFinished(finishedTasksJsonString, dateStr);

        event.stopPropagation();
    });


</script>

<!-- ----------------------------------------------------------------------- -->

<!--快捷键-->
<script>

    // 参考资料：https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery
    $(window).bind('keydown', function(event) {

        if (event.ctrlKey || event.metaKey) {
            switch (event.key) {
                case "s":
                case "S":
                    // 按下 ctrl + s 时保存。
                    event.preventDefault();
                    $(":focus").focusout();
                    break;
                case "ArrowUp":
                    // 按下 Ctrl + ↑ 时折叠所有
                    event.preventDefault();
                    $(".closeAll").click();
                    break;
                case "ArrowDown":
                    // 按下 Ctrl + ↓ 时展开所有
                    event.preventDefault();
                    $(".openAll").click();
                    break;
                case "ArrowLeft":
                    keyGPressed = 0;
                    $(".viewPreWeek").click()
                    break
                case "ArrowRight":
                    keyGPressed = 0;
                    $(".viewNextWeek").click()
                    break
                case "0":
                    // 数字键 0（包括数字键与小键盘）
                    // case "0" 的 引号不可省略
                    keyGPressed = 0;
                    $(".viewThisWeek").click()
            }
        }

    });

</script>

<!-- ----------------------------------------------------------------------- -->

<!-- 添加「返回顶部按钮」 -->
<script src="../resources/vanilla-back-to-top/index.js"></script>
<script src="../resources/vanilla-back-to-top/config.js"></script>

<!-- ----------------------------------------------------------------------- -->

</body>
</html>
